'use strict';
const stringify  = require('json-stringify-deterministic');
const sortKeysRecursive  = require('sort-keys-recursive');
const { Contract } = require('fabric-contract-api');

class AssetTransfer extends Contract {

    //使用给定参数创建货物
    async CreateAsset(ctx, id, goods,amount, owner, price,time) {
        const exists = await this.AssetExists(ctx, id);
        if (exists) {
            throw new Error(`The asset ${id} already exists`);
        }

        const asset = {
            ID: id,
            Goods:goods,
            Amount: amount,
            Owner: owner,
            Price: price,
            Time:time
        };
        await ctx.stub.putState(id, Buffer.from(stringify(sortKeysRecursive(asset))));
        return JSON.stringify(asset);
    }

    //根据给定id查询账单
    async ReadAsset(ctx, id) {
        let assetJSON = await ctx.stub.getState(id);
        if (!assetJSON || assetJSON.length === 0) {
            assetJSON={
                "a":"0"
            };
        }
        return assetJSON.toString();
    }

    //判断给定id的账单是否存在
    async AssetExists(ctx, id) {
        let assetJSON = await ctx.stub.getState(id);
        return assetJSON && assetJSON.length > 0;
    }

    //对资产进行交易，交易将更新持有人和时间
    async TransferAsset(ctx, id, newOwner, time) {
        let assetString = await this.ReadAsset(ctx, id);
        let asset = JSON.parse(assetString);
        let newStr=asset.Owner+"+"+newOwner;
        asset.Owner = newStr;
        asset.Time=time;
        await ctx.stub.putState(id, Buffer.from(stringify(sortKeysRecursive(asset))));
        //putState要求key必须是唯一的，不能用多个key值来确定某个数据
        //这就意味着couchDB中的数据必须有一项是独一无二的，否则无法完成交易
        return JSON.stringify(asset);
    }
}

module.exports = AssetTransfer;
